package com.eportal.action.background;

import com.eportal.action.BaseAction;
import com.eportal.domain.*;
import com.eportal.exception.MdKnownRunTimeException;
import com.eportal.service.*;
import com.eportal.util.CityUtil;
import com.eportal.util.DateUtils;
import com.eportal.util.HomePageConfig;
import com.eportal.util.SmsHelper;
import com.framework.jqgrid.JqGridPager;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 社区管理
 * @author chencheng
 *
 */
public class TCommunityAction extends BaseAction implements ModelDriven<TCommunity> {

    /**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private static Logger log = Logger.getLogger(TCommunityAction.class.getName());

    private Map<String, Object> result = new HashMap<String, Object>();

    @Autowired
	private TAgentService tAgentService;
    @Autowired
    private TCommunityService tCommunityService;
    @Autowired
    private TUsersService tUsersService;
    @Autowired
    private CityService cityService;
    @Autowired
    private SysOptService sysOptService;
    @Autowired
    private TLocksService tLocksService;
    @Autowired
    private TKeysService tkeysService;
	/**
     * 社区管理
     */
    public String listView() {
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	getRequest().setAttribute("userRole", userRole);
    	getRequest().setAttribute("agtCode", getRequest().getParameter("agtCode"));
    	if (userRole == 1) {
    		getRequest().setAttribute("agtCodeA", getRequest().getParameter("agtCode"));
		}
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	getRequest().setAttribute("rLevel", user.getrLevel());
    	return SUCCESS;
    }

    /**
     * 社区列表
     */
    public void page() throws Exception {
    	JqGridPager page = new JqGridPager();
        String areaCode = getRequest().getParameter("areaCode");
        String agtCode = getRequest().getParameter("agtCode");
    	String communityId = getRequest().getParameter("communityId");
    	StringBuilder where = new StringBuilder(" 1=1 ");
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	if (userRole == 1 || userRole == 2 || userRole == 21) {
    		if (StringUtils.isNotBlank(agtCode)) {
                where.append(" and  t.agtCode = '");
                where.append(agtCode);
                where.append("'");
            }
    		if (StringUtils.isNotBlank(communityId)) {
                where.append(" and  t.sid = '");
                where.append(communityId);
                where.append("'");
            }
    		if (userRole == 21) {
    			where.append(" and a.sysoptId =");
    			where.append(user.getSid());
    		}
    	}
    	if (userRole == 3 || userRole == 4) {
    		where.append(" and t.agtCode ='");
    		where.append(user.getAgtCode());
    		where.append("'");
    		if (StringUtils.isNotBlank(communityId)) {
                where.append(" and  t.sid = '");
                where.append(communityId);
                where.append("'");
            }
    	}
    	if (userRole == 5 || userRole == 6) {
    		where.append(" and t.sid ='");
    		where.append(user.getCommunityId());
    		where.append("'");
    	}
    	if (StringUtils.isNotBlank(areaCode)) {
    		where.append(" and  substr(t.areaCode,1,");
        	if(CityUtil.isMunicipalities(areaCode)){//直辖市
        		where.append("2) = '");
        		where.append(areaCode.substring(0, 2));
        		where.append("'");
        	}else{
        		where.append("4) = '");
        		where.append(areaCode.substring(0, 4));
        		where.append("'");
        	}
        }
    	page.setWhere(where.toString());
        setPage(getRequest(), page);

        setPage(getRequest(), page);
        List<TCommunity> tCommunitys = tCommunityService.list(page);
        jqGridQueryMap(TCommunity.class, getRequest(), tCommunitys, getResponse(), page);
    }

    private String sqlWhere() {
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	StringBuilder where = new StringBuilder(" 1=1 ");
    	if (userRole == 5 || userRole == 6) {
    		where.append(" and sid ='");
    		where.append(user.getCommunityId());
    		where.append("'");
    	}
		if (userRole == 3 || userRole == 4) {
			where.append(" and agtCode ='");
			where.append(user.getAgtCode());
			where.append("'");
		}
		return where.toString();
	}

	/**
     * 社区列表
     */
    public void list() throws Exception {
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	String agtCode = getRequest().getParameter("agtCode");
    	StringBuilder where = new StringBuilder("select t from TCommunity t,TAgent a where t.agtCode=a.agtCode ");
    	if (userRole == 5 || userRole == 6) {
    		where.append(" and t.sid ='");
    		where.append(user.getCommunityId());
    		where.append("'");
    	}
		if (StringUtils.isBlank(agtCode)) {
			if (userRole == 3 || userRole == 4) {
				where.append(" and t.agtCode ='");
				where.append(user.getAgtCode());
				where.append("'");
			}else if (userRole == 21) {
    			where.append(" and a.sysoptId =");
    			where.append(user.getSid());
			}
		}else{
			where.append(" and t.agtCode ='");
			where.append(agtCode);
			where.append("'");
		}
    	List<TCommunity> TCommunitys = tCommunityService.list(where.toString());
        responseBody(TCommunitys);
    }
    /**
     * 开门惊喜，根据agtCodes查询list
     */
    public void listByAgtCodes() throws Exception {
    	String agtCodes = getRequest().getParameter("agtCodes");
    	List<TCommunity> TCommunitys = tCommunityService.listByAgtCodes(agtCodes);
    	responseBody(TCommunitys);
    }

    /**
     * 社区修改
     */
    public String editView() {
    	Map<String, String> tCommunity = tCommunityService.getBySql(getModel().getSid());
        getRequest().setAttribute("tCommunity", tCommunity);
        return SUCCESS;
    }

    /**
     * 社区修改保存
     */
    public void update(){
    	TCommunity tCommunity  = getModel();
    	String adminUserName = getRequest().getParameter("adminUserName");
    	String password = getRequest().getParameter("password");
    	result = tCommunityService.updateMethod(tCommunity,adminUserName,password);
        responseBody(result);
    }

    /**
     * 社区修改资料
     */
    public String detailView() {
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	String communityId = user.getCommunityId();
    	String homePageConfig = HomePageConfig.SHEQUXX;
    	String[] str = homePageConfig.split(",");
		getRequest().setAttribute("mpid", Integer.parseInt(str[0]));
    	getSession().setAttribute("mpid", Integer.parseInt(str[0]));
    	if ("0".equals(communityId)) {
    		return "error";
		}else{
	    	TAgent tagent = tAgentService.get(user.getAgtCode());
	    	getRequest().setAttribute("agtName",tagent.getAgtName());
	    	Map<String, String> tCommunity = tCommunityService.getBySql(Long.parseLong(user.getCommunityId()));
	        getRequest().setAttribute("tCommunity", tCommunity);
	    	getRequest().setAttribute("rLevel", user.getrLevel());
			return SUCCESS;
		}
    }


	/**
     * 社区增加
     */
    public String addView() {
        return SUCCESS;
    }
    /**
     * 社区新增保存
     */
    public void add() {
    	TCommunity tCommunity  = getModel();
    	result = tCommunityService.addMethod(tCommunity);
        responseBody(result);
    }


    /**
     * 社区删除
     */
    public void delete(){
    	String param_ids = getRequest().getParameter("ids");
    	result = tCommunityService.deleteMethod(param_ids);
        responseBody(result);
    }

    /**
     * 社区注册
     * @throws IOException
     */
    public String tComuRegister() throws IOException {
    	String inviteUrl = getRequest().getParameter("u");
    	if (StringUtils.isBlank(inviteUrl)) {
    		getRequest().setAttribute("message","该连接验证码无效");
    		 return "error";
		}
    	getRequest().setAttribute("inviteUrl",inviteUrl);
    	inviteUrl=inviteUrl.substring(0,inviteUrl.length()-14);
    	String agtCode= inviteUrl.substring(0,inviteUrl.length()/2);
    	TAgent tagent = tAgentService.get(agtCode);
    	if (tagent == null) {
    		getRequest().setAttribute("message","该连接验证码无效");
   		 	return "error";
		}
    	getRequest().setAttribute("agtName",tagent.getAgtName());
    	getRequest().setAttribute("agtCode",agtCode);
        return "tComuRegister";
    }

    /**
     * 社区新增保存
     */
    public void tComuAdd() throws IOException {
    	TCommunity tCommunity  = getModel();
    	String inviteUrl = getRequest().getParameter("inviteUrl");
    	if (StringUtils.isBlank(inviteUrl)) {
    		 result.put("code", 0);
	         result.put("msg", "该连接验证码无效");
	         responseBody(result);
	         return;
		}
    	StringBuffer sb = new StringBuffer(" inviteUrl='");
		sb.append(inviteUrl);
		sb.append("'");
    	TCommunity communityExist = tCommunityService.get(sb.toString());
    	if (communityExist != null) {
    		 result.put("code", 0);
	         result.put("msg", "该连接已注册过，无法使用");
	         responseBody(result);
	         return;
		}
    	tCommunity.setDepartName(tCommunity.getCommunityName());
    	result = tCommunityService.tComuAddMethod(tCommunity);
        responseBody(result);
    }
    /**
     * 锁厂用户注册
     */
    public String tComuLockRegister() {
        return "tComuLockRegister";
    }
    /**
     * 锁厂用户注册APP页面
     */
    public String registerLockApp() {
    	String userId = (String) getSession().getAttribute("app_userid");
    	TUsers tUsers = tUsersService.getByUserid(userId);
    	if (tUsers != null) {
    		getRequest().setAttribute("tel", tUsers.getTel());
    		getRequest().setAttribute("appid", tUsers.getAppId());
		}else{
			getRequest().setAttribute("loginedFlag", "0");
		}
    	String type = getRequest().getParameter("type");
    	if(type==null){
    		type="1";//默认为正常的注册，type=2是硬件转移注册
    	}
    	//在转移是会传pid及checkcode的参数
    	if(getRequest().getParameter("pid")!=null){
    		getRequest().setAttribute("pid", getRequest().getParameter("pid"));
        	getRequest().setAttribute("checkcode", getRequest().getParameter("checkcode"));
    	}else if(getRequest().getSession().getAttribute("register_add_pid")!=null){
    		getRequest().setAttribute("pid", getRequest().getParameter("register_add_pid"));
        	getRequest().setAttribute("checkcode", getRequest().getParameter("register_add_checkcode"));
    	}

    	getRequest().setAttribute("type", getRequest().getParameter("type"));
    	return "registerLockApp";
    }

    /**
     * 锁厂客户注册保存
     */
    public void tComuLockAdd() throws IOException {
    	try {
    		TCommunity tCommunity  = getModel();
    		String pid = getRequest().getParameter("pid");
    		String checkCode = getRequest().getParameter("checkCode");
    		String yzm = getRequest().getParameter("yzm");//短信验证码
    		String lockName = getRequest().getParameter("lockName");//智能锁名称
    		String type= getRequest().getParameter("type");//1:正常注册，2：转换主人
    		String typeAPP= getRequest().getParameter("typeAPP");
    		String appid = getRequest().getParameter("appid");
    		String pwd = getRequest().getParameter("pwd");
    		String loginedFlag = getRequest().getParameter("loginedFlag");

    		if("2".equals(type)){
    			String transferPid = (String)getSession().getAttribute("transferPid");
    			if(!pid.equals(transferPid)){
    				result.put("code", 0);
        			result.put("msg", "输入的pid和需要转移的pid不一致，请检查信息或重新尝试");
        			responseBody(result);
        			return;
    			}
    		}
    		tCommunity.setComContact(tCommunity.getCommunityName());
    		tCommunity.setDepartName(tCommunity.getCommunityName());
    		if(tCommunity.getAreaCode()==null||tCommunity.getAreaCode().length()==0){//默认设置一个地区
    			tCommunity.setAreaCode("330106");
    		}
    		City city = (City) cityService.get("from City where dm='"+tCommunity.getAreaCode()+"'");
    		if (city != null) {
    			tCommunity.setCityCode(city.getDescribed());
			}else{
				result.put("code", 0);
    			result.put("msg", "找不到区划码，请联系技术人员处理");
    			responseBody(result);
    			return;
			}
    		if("0".equals(typeAPP)){//app注册
    			String userId = (String) getSession().getAttribute("app_userid");
    			if(userId!=null){
    				TUsers user = tUsersService.getByUserid(userId);
    				tCommunity.setDepartTel(user.getTel());
           			try{
        				if(user.getAuName()==null){
    						user.setAuName(tCommunity.getDepartName());
    						tUsersService.update(user);
    					}
        			}catch(Exception e){
        				log.error(this, e);
        			}
    			}else{
    				boolean bool = SmsHelper.checkSMSValidCache(tCommunity.getDepartTel(),yzm);
                	if (!bool) {
                		result.put("code", 0);
            			result.put("msg", "验证码不正确");
            			responseBody(result);
            			return;
                	}
    			}


    			if("2".equals(loginedFlag)){//手机号已注册，但是当前未登录app的情况
    				boolean bool = SmsHelper.checkSMSValidCache(tCommunity.getDepartTel(),yzm);
                	if (!bool) {
                		result.put("code", 0);
            			result.put("msg", "验证码不正确");
            			responseBody(result);
            			return;
                	}
            		TUsers user =  tUsersService.getByWhere("appid='"+appid+"' and tel='"+tCommunity.getDepartTel()+"'");
            		if(user!=null){
            			Sysopt opt = sysOptService.getByAppUserid(user.getUserId());
            			getRequest().getSession().setAttribute("app_userid", user.getUserId());
            			getRequest().getSession().setAttribute("user",opt);
            			try{
            				if(user.getAuName()==null){
        						user.setAuName(tCommunity.getDepartName());
        						tUsersService.update(user);
        					}
            			}catch(Exception e){
            				log.error(this, e);
            			}
            			if(opt!=null){
            				TLock tlock = new TLock();
            				tlock.setPid(pid);
            				tlock.setCheckCode(checkCode);
            				result = tLocksService.addMethod(tlock,"1",opt);//todo Updated by Saber on 2017/7/27 上午11:31
            				if("1".equals(result.get("code"))){
            					result.put("tel",tCommunity.getDepartTel());
                				result.put("userid",user.getUserId());
                				result.put("token",user.getToken());
                				try{
                	        		//智能锁app用户新增设备时，自动为其添加一把钥匙
                	        		String userid = (String)getRequest().getSession().getAttribute("app_userid");
                	        		if(userid!=null){
                	        			TUsers tuser = tUsersService.getByUserid(userid);
                	        			if(tuser!=null){
                	        				TLock lock  = tLocksService.getByPid(pid);
                	        				if(lock!=null){
                	        					List list = new ArrayList();
                	        					list.add(lock);
                	        					lock.setCommunityId(opt.getCommunityId());
                	        					lock.setStatus("1");//设置已安装
                	        					lock.setInstallLockName(lockName);
                	        					lock.setInstallTime(new Timestamp(System.currentTimeMillis()));
                	        					tLocksService.update(lock);
                	        					tkeysService.SyncTo(tuser, list, DateUtils.formatDate(DateUtils.addYear(new Date(), 20)), lock.getAgtCode(), null);//分配一把20年的钥匙给用户

                	        				}
                	        			}
                	        		}
                				}catch(Exception e){
                					log.error(this,e);
                				}
                				responseBody(result);
                    			return;	
            				}else{
            					responseBody(result);
                    			return;
            				}
            			}else{
            				log.info("没有对应的管理端账户、继续执行");
            			}
            		}else{
            			result.put("code", 0);
            			result.put("msg", "获取用户信息失败，请重新登录尝试");
            			responseBody(result);
            			return;
            		}
            	}

    			tCommunity.setComm("");
    			tCommunity.setAdminUser(tCommunity.getDepartTel());
    			tCommunity.setType("2");
        		result = tCommunityService.tComuLockAddMethod(tCommunity,pid,checkCode,lockName,type,typeAPP,appid,pwd);
        		result.put("tel",tCommunity.getDepartTel());
    		}else if("1".equals(typeAPP)){//pc端注册
    			tCommunity.setDepartTel(tCommunity.getAdminUser());
    			tCommunity.setType("2");
        		result = tCommunityService.tComuLockAddMethod(tCommunity,pid,checkCode,lockName,type,typeAPP,appid,pwd);
    		}else {
    			result.put("code", 0);
    			result.put("msg", "无法判断注册类型，请刷新重试");
    			responseBody(result);
    			return;
    		}
//    		String userId = (String) getSession().getAttribute("app_userid");
//    		boolean bool = SmsHelper.checkSMSValidCache(tCommunity.getDepartTel(),yzm);
//        	if (!bool) {
//        		result.put("code", 0);
//    			result.put("msg", "验证码不正确");
//    			responseBody(result);
//    			return;
//    		}else{
//    			tCommunity.setType("2");
//        		result = tCommunityService.tComuLockAddMethod(tCommunity,pid,checkCode,lockName,type);
//    		}
		} catch (MdKnownRunTimeException e) {
			result.put("code", 0);
  	        result.put("msg", e.getMessage());
  	      log.error(this, e);
		}catch (Exception e) {
			result.put("code", 0);
  	        result.put("msg", "注册失败");
  	      log.error(this, e);
		}
    	responseBody(result);
    }

    /**
     * 审核小区
     */
    public String auditListView() {
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	if (userRole == 1) {
    		getRequest().setAttribute("agtCode", getRequest().getParameter("agtCode"));
    	}else{
    		getRequest().setAttribute("agtCode", "");
    	}
        return SUCCESS;
    }

    /**
     * 审核小区列表
     * @throws Exception
     */
    public void auditList() throws Exception {
    	 JqGridPager page = new JqGridPager();
    	 Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	 String agtCode = getRequest().getParameter("agtCode");
    	 if (StringUtils.isBlank(agtCode)) {
    		 agtCode = user.getAgtCode();
		 }
         setPage(getRequest(), page);
         page.setSord(null);
         page.setSidx(null);
         List<TCommunity> tCommunitys = tCommunityService.auditList(page,agtCode);
         jqGridQueryMap(TAgent.class, getRequest(), tCommunitys, getResponse(), page);
    }

    /**
     * 小区审核
     */
    public void audit(){
    	try {
	    	String sid = getRequest().getParameter("sid");
	    	String status = getRequest().getParameter("status");
	    	String appSid = getRequest().getParameter("appSid");
	    	if(StringUtils.isBlank(appSid)){
	    		result.put("code", 0);
	  	        result.put("msg", "关联APP必须选择");
	  	        responseBody(result);
	  	        return;
	    	}
	    	String comm = getRequest().getParameter("comm");
    		result = tCommunityService.auditMethod(sid,status,appSid,comm);
		} catch (MdKnownRunTimeException e) {
			result.put("code", 0);
  	        result.put("msg", e.getMessage());
  	      log.error(this, e);
		}catch (Exception e) {
			result.put("code", 0);
  	        result.put("msg", "小区审核失败");
  	      log.error(this, e);
		}
        responseBody(result);
    }

    /**
     * 邀请注册
     */
    public String inviteCommunity(){

    	 String str = getRequest().getRequestURL().toString();
    	 str = str.substring(0,str.lastIndexOf("admin"));
    	 Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	 String agtCode = null;
    	 int userRole =  (Integer) getSession().getAttribute("userRole");
    	 if (userRole == 1) {
    		 agtCode = getRequest().getParameter("agtCode");
    	 }
    	 if (StringUtils.isBlank(agtCode)) {
    		 agtCode = user.getAgtCode();
		 }
    	 SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmss");
    	 TAgent tagent = tAgentService.get(agtCode);
    	 StringBuilder url = new StringBuilder(str);
    	 url.append("register/tComuRegister.action?u=");
    	 if (tagent == null) {
    		 getRequest().setAttribute("url",url.toString());
    		 return SUCCESS;
		}
    	 url.append(agtCode).append(tagent.getSid()).append(sd.format(new Date()));
    	 getRequest().setAttribute("url",url.toString());
    	 return SUCCESS;
    }

    /**
     * 审批拒绝原因填写
     * @return
     */
    public String refuse(){
    	getRequest().setAttribute("sid", getRequest().getParameter("sid"));
    	getRequest().setAttribute("status", getRequest().getParameter("status"));
    	return SUCCESS;
    }

    /**
     * 社区报表详情
     * @return
     */
    public String tcomuReportsView(){
    	getRequest().setAttribute("tCommunityId", getRequest().getParameter("tCommunityId"));
    	String homePageConfig = HomePageConfig.TCOMUREPORTS;
    	String[] str = homePageConfig.split(",");
		getRequest().setAttribute("mpid", Integer.parseInt(str[0]));
    	getSession().setAttribute("mpid", Integer.parseInt(str[0]));
    	return SUCCESS;
    }

    /**
     * 社区报表详情
     * @throws Exception
     * @throws IOException
     */
    public void tcomuReports() throws Exception{
    	JqGridPager jqGridPager = new JqGridPager();
    	 List<Map<String, String> > dataList = new ArrayList<Map<String, String> >();
    	 String tCommunityId = getRequest().getParameter("tCommunityId");
		 Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	 if(StringUtils.isBlank(tCommunityId)){
    		 tCommunityId = user.getCommunityId();
    	 }
    	 dataList = tAgentService.tcomuReports(user.getAgtCode(),tCommunityId);
    	 jqGridQueryMap(Map.class, getRequest(), dataList, getResponse(), jqGridPager);
    }

    private TCommunity tCommunity = new TCommunity();

    @Override
    public TCommunity getModel() {
        return tCommunity;
    }
}
